package com.deep.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.deep.auth.annotation.ApiController;
import com.deep.auth.feign.MemberFeignService;
import com.deep.auth.model.vo.SocialUserVO;
import com.deep.common.model.constant.AuthConstant;
import com.deep.common.model.dto.MemberResponseVO;
import com.deep.common.utils.HttpUtils;
import com.deep.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 *
 * @author Deep
 * @date 2022/2/7
 */
@Slf4j
@Controller
@RequestMapping("/api/auth/oauth2.0")
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 社交登录
     *
     * @param code 信息码（用来换取token）
     */
    // http://auth.mall.com/api/auth/oauth2.0/gitee/success?code=f248751f7c2386e755cf1a6fac9917737e39610fdff66de770686729a499e99d
    @GetMapping("/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        // 请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("code", code);
        paramMap.put("client_id", "672b6b1a905b8d2395e045349531e5384bfe81423359460142e9d2f388573795");
        paramMap.put("redirect_uri", "http://auth.mall.com/api/auth/oauth2.0/gitee/success");
        paramMap.put("client_secret", "f3fae5d8c055d58c192b05112ff75f9e0c3f957b3c6f524461bc9cc581367748");

        // 1、根据code换取access_token
        HttpResponse response =
                HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), paramMap, new HashMap<>());

        // 2、处理
        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取到了access_token
            // String json = JSON.toJSONString(response.getEntity());
            String json = EntityUtils.toString(response.getEntity());       // 获取到json串
            SocialUserVO socialUser = JSON.parseObject(json, SocialUserVO.class);

            System.out.println("登录后用code换取的token值：" + socialUser.getAccess_token());

            // 从token获取社交用户
            //1）、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息，以后这个社交账号就对应指定的会员）
            // 调用远程服务(登录或者注册这个社交用户)
            R oauthLogin = memberFeignService.oauthLogin(socialUser);
            if (oauthLogin.getCode() == 0) {
                MemberResponseVO memberResVO = oauthLogin.getData("data", new TypeReference<MemberResponseVO>() {
                });

                log.info("登录成功：用户信息：\n{}", memberResVO);

                // 1、第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookie
                // 以后浏览器访问哪个网站就会带上这个网站的cookie
                // TODO 1、默认发的令牌。当前域（解决子域session共享问题）（即扩大作用域范围）
                // TODO 2、使用JSON的序列化方式来序列化对象到Redis中
                session.setAttribute(AuthConstant.LOGIN_USER, memberResVO);

                //2、登录成功跳回首页
                return "redirect:http://mall.com/api/product/";
            } else {
                return "redirect:http://auth.mall.com/api/auth/login.html";
            }
        } else {
            return "redirect:http://auth.mall.com/api/auth/login.html";
        }
    }
}
